package com.uchengwang.ui.cm_ui.me.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.ClubConfig;
import com.uchengwang.functions.http.config.RyConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.me.adapter.AccessApplyAdapter;
import com.uchengwang.ui.cm_ui.me.bean.AccessApplyBean;
import com.uchengwang.ui.cm_ui.me.bean.AccessApplyListBean;
import com.uchengwang.ui.cm_ui.rychat.bean.InviteUserBean;
import com.uchengwang.ui.cm_ui.rychat.bean.RyUserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.model.Conversation;

/**
 * Created by U城网 on 2017/8/11.
 */

public class ClubAccessApplyNewActivity extends BaseWithTitleActivity implements View.OnClickListener{

    private RecyclerView apply_rv;
    private AccessApplyAdapter adapter;
    private LinearLayout bm_linear;
    private AppCompatCheckBox agreeNo_box;
    private TextView apply_agree, agreeNo_all;//同意报名，选中人数
    private List<AccessApplyBean> list;
    private long recruitId;//社团纳新ID
    private long groupID, ownerId;
    private List<RyUserBean> memmbers;
    private String groupName;

    private int page = 1;//当前页  每页请求多少数据
    private int totlaPagers ;//总页数【服务器返回】
    private PtrClassicFrameLayout agreeNo_refresh;
    private RecyclerAdapterWithHF mAdapter;

    private boolean isAllCheck = false;//是不是全选
    private int allCount;//选择的总人数

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //点击增减
                    boolean isCheck = (boolean) msg.obj;
                    if (isAllCheck){
                        if (isCheck){
                            allCount++;
                            agreeNo_all.setText("全选 "+allCount);
                        }else {
                            allCount--;
                            if (allCount <=0){
                                agreeNo_all.setText("全选");
                                agreeNo_box.setChecked(false);
                            }else {
                                agreeNo_all.setText("全选 "+allCount);
                            }

                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_agree_yes);

        recruitId = getIntent().getLongExtra(BaseConfig.RECRUIT_ID, -1);
        groupID = getIntent().getLongExtra(BaseConfig.GROUP_ID, 0);
        groupName = getIntent().getStringExtra(BaseConfig.GROUP_NAME_UCW);

        setTitle("已报名");



        initView();
    }

    private void initView() {
        agreeNo_refresh = (PtrClassicFrameLayout) findViewById(R.id.agreeYes_refresh);


        apply_rv = (RecyclerView) findViewById(R.id.fm_agreeyes_rv);
        bm_linear = (LinearLayout) findViewById(R.id.fm_agreeyes_bottom);
        bm_linear.setVisibility(View.VISIBLE);
        agreeNo_box = (AppCompatCheckBox) findViewById(R.id.fm_agreeyes_box);
        agreeNo_all = (TextView) findViewById(R.id.fm_agreeyes_all);
        apply_agree = (TextView) findViewById(R.id.fm_agreeyes_agree);//同意报名

        apply_agree.setOnClickListener(this);

        if (groupID <1){
            apply_agree.setText("创建群聊");
        }else {
            apply_agree.setText("邀请入群");
        }

        initData();

    }

    private void initData() {

        agreeNo_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                LoadingUtils.getUtils().loading(ClubAccessApplyNewActivity.this);
                if (b){
                    //全部选中
                    list = adapter.getData();
                    int count = 0;
                    if (list != null && list.size()>0){
                        for (AccessApplyBean bean : list){
                            if (!adapter.isMember(bean.getUid())){
                                bean.setCheck(true);
                                count++;
                            }
                        }
                        agreeNo_all.setText("全选 "+(count==0 ?"":count));
                        agreeNo_all.setTextColor(getResources().getColor(R.color.ustudy_no_choose));
                        adapter.notifyDataSetChanged();
                    }
                }else {
                    //取消全选
                    if (list != null && list.size()>0){
                        for (AccessApplyBean bean : list){
                            bean.setCheck(false);
                        }
                        agreeNo_all.setText("全选");
                        agreeNo_all.setTextColor(getResources().getColor(R.color.sign_color));
                        adapter.notifyDataSetChanged();
                    }
                }

                LoadingUtils.getUtils().hide();
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(this);

        adapter = new AccessApplyAdapter(this, handler);
        mAdapter = new RecyclerAdapterWithHF(adapter);
        apply_rv.setLayoutManager(manager);
        apply_rv.setAdapter(mAdapter);

        agreeNo_refresh.setAutoLoadMoreEnable(true);
        agreeNo_refresh.setLoadMoreEnable(true);

        agreeNo_refresh.postDelayed(new Runnable() {

            @Override
            public void run() {
                agreeNo_refresh.autoRefresh(true);
            }
        }, 150);

        agreeNo_refresh.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                agreeNo_refresh.loadMoreComplete(true);
                getApplys(true);
            }
        });

        agreeNo_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                page++;
                if (page <= totlaPagers){
                    //当前请求页大于总页数，不再请求
                    getApplys(false);
                } else {
                    agreeNo_refresh.loadMoreComplete(false);
                }
            }
        });

    }

    /**
     * 获取报名人数信息
     * */
    private void getApplys(final boolean isRefresh){
        MapRequest map = new MapRequest();
        map.put(BaseConfig.PAGE, page);
        map.put(BaseConfig.PERPAGE, 10);
        HttpManager.newInstance(this).query(ClubConfig.ClubEnroll.method_get, ClubConfig.ClubEnroll.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                if (isRefresh){
                    agreeNo_refresh.refreshComplete();
                }else {
                    agreeNo_refresh.loadMoreComplete(true);
                }
                UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "获取失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                if (isRefresh){
                    agreeNo_refresh.refreshComplete();
                }else {
                    agreeNo_refresh.loadMoreComplete(true);
                }
                if (status != 0 || data == null){
                    return;
                }

                if (!TextUtils.isEmpty(data)){
                    AccessApplyListBean bean = JsonUtils.getManager().stringToBean(data, AccessApplyListBean.class);
                    totlaPagers = bean.getTotalPage();
                    List<AccessApplyBean> beanList = bean.getData();
                    if (beanList != null && beanList.size() > 0){
                        if (isRefresh){
                            adapter.setData(beanList);
                        }else {
                            adapter.getData().addAll(beanList);
                            adapter.notifyDataSetChanged();
                        }

                        //获取到群成员
                        if (memmbers == null || BaseConfig.isRelease){
                            getGroupMembers();
                        }else {
                            adapter.setMembers(memmbers);
                        }

                    }
                }
            }
        });
    }

    private String[] longs;
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.fm_agreeyes_agree://邀请入群
                LoadingUtils.getUtils().loading(this);
                List<String> longList = new ArrayList<>();
                List<AccessApplyBean> chechBeans = new ArrayList<>();

                if (adapter!= null){
                    List<AccessApplyBean> list = adapter.getData();
                    int size = list.size();
                    for (int i=0; i<size; i++){
                        //将选中的对象筛选出来
                        AccessApplyBean b = list.get(i);
                        if (b.isCheck()){
                            chechBeans.add(b);
                            longList.add(String.valueOf(b.getUid()));
                        }
                    }

                    int lenght =longList.size();
                    longs = new String[lenght];
                    for (int i=0; i<lenght; i++){
                        longs[i] = longList.get(i);
                    }
                }

                if (longs == null || longs.length <=0){
                    LoadingUtils.getUtils().hide();
                    UCommonUtil.getUtil().showToast(this, "请选择");
                    return;
                }

                if (groupID <1){
                    //创建群聊
                    createGroup(longs);
                }else {
                    addMember(chechBeans);
                }
                break;
        }
    }

    /**
     * 调取环信的接口,获取群组信息
     * */
    private void getGroupMembers(){
        if (groupID <1){
            return;
        }
        RyGroupManager.getManager().getGroupMembers(this, groupID, 1, 999, new OnHttpResultListener<RyUserBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<RyUserBean> list) {
                if (list == null || list.size() <1){
                    return;
                }
                memmbers = list;
                if (memmbers != null && memmbers.size() >0){
                    adapter.setMembers(memmbers);
                }
            }
        });

    }

    /**
     * 创建社团纳新群聊
     * */
    private void createGroup(String[] ms){
        LoadingUtils.getUtils().loading(this);

        MapRequest map = new MapRequest();
        map.put(BaseConfig.USER_LIMIT, 500);
        map.put(BaseConfig.GROUP_DESC, UChengApplication.nickName+"纳新群");
        map.put(BaseConfig.GROUP_LOGO, BaseConfig.ShortTimeLogo);
        map.put(BaseConfig.GROUP_NAME_UCW, UChengApplication.nickName+"纳新群");
        map.put(BaseConfig.IS_PUBLIC, true);
        map.put(BaseConfig.IS_NEED_APPLY, true);
        map.put(BaseConfig.ORG_ID, UChengApplication.clubId);
        map.put(BaseConfig.ORG_TYPE, 0);//代表社团
        map.put(BaseConfig.MEMBER_ROLE, BaseConfig.STUDENT_ROLE);

        map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);

        map.put(BaseConfig.CREATE_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.CREATE_UID, UCommonUtil.getUtil().getId());

        map.put(BaseConfig.ADMIN_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.ADMIN_UID, UCommonUtil.getUtil().getId());

        if (ms != null && ms.length >0){
            map.put(BaseConfig.USER_IDS, ms);
        }

        HttpManager.newInstance(this).query(RyConfig.RecruitGroup.method, RyConfig.RecruitGroup.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "创建失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                if (status ==0 ){
                    BaseConfig.changeGroup = true;
                    UCommonUtil.getUtil().toChatActiviy(ClubAccessApplyNewActivity.this, data, Conversation.ConversationType.GROUP, UChengApplication.nickName+"纳新群");

                    UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "创建成功");
                    ClubAccessApplyNewActivity.this.finish();
                    return;
                }

                if (status ==1){
                    UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "你已经创建过");
                }else {
                    UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, msg);
                }
            }
        });
    }


    /**
     * 添加群成员
     * */
    private void addMember(final List<AccessApplyBean> list){
        List<InviteUserBean> userBeanList = new ArrayList<>();
        for (AccessApplyBean userBean : list){
            //选中邀请的好友
            InviteUserBean inviteUserBean = new InviteUserBean();
            inviteUserBean.setGroupId(groupID);
            inviteUserBean.setGroupName(groupName);
            inviteUserBean.setInviteMsg("欢迎您");
            inviteUserBean.setToUid(userBean.getUid());
            inviteUserBean.setToNickName(userBean.getNickName());
            inviteUserBean.setToUserAvatar(userBean.getUserAvatar());

            userBeanList.add(inviteUserBean);
        }

        RyGroupManager.getManager().inviteMember(this, userBeanList, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                LoadingUtils.getUtils().hide();
                if (stutas ==0){
                    List<RyUserBean> ryUserList = new ArrayList<RyUserBean>();
                    for (AccessApplyBean bean :list){
                        RyUserBean b = new RyUserBean();
                        b.setMemberUid(bean.getUid());
                        ryUserList.add(b);
                    }
                    memmbers.addAll(ryUserList);
                    adapter.setMembers(memmbers);

                    UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "邀请成功");
                }else {
                    UCommonUtil.getUtil().showToast(ClubAccessApplyNewActivity.this, "邀请失败, 请重试");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        List<AccessApplyBean> l = adapter.getData();
        l.clear();
        l = null;

        if (memmbers != null){
            memmbers.clear();
            memmbers = null;
        }

    }
}
